using System;
using System.Configuration;
using System.Reflection;
using Castle.MonoRail.Framework;

namespace AndyPike.Commons.Web.MonoRail.Binders
{
    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public class CaptchaBindAttribute : Attribute, IParameterBinder
    {
        private const string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";  
        private const string RESPONSE_FIELD_KEY = "recaptcha_response_field";

        public object Bind(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)
        {
            var captchaChallengeValue = context.Request[CHALLENGE_FIELD_KEY];  
            var captchaResponseValue = context.Request[RESPONSE_FIELD_KEY];  
            var captchaValidtor = new Recaptcha.RecaptchaValidator  
                                      {
                                          PrivateKey = ConfigurationManager.AppSettings["recaptcha.private"],
                                          RemoteIP = context.UnderlyingContext.Request.UserHostAddress,  
                                          Challenge = captchaChallengeValue,  
                                          Response = captchaResponseValue  
                                      };  

            var recaptchaResponse = captchaValidtor.Validate();  

            return recaptchaResponse.IsValid;
        }

        public int CalculateParamPoints(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)
        {
            if (parameterInfo.ParameterType == typeof(bool))
                return 10;
            
            return 0;
        }
    }
}